package edu.njfu.networkdemo.utils

import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.URL
import java.net.URLConnection

object FileDownloadUtil{
    public fun downloadFile(urlStr: String): File? {
        var url: URL? = null
        var input: InputStream? = null
        var output: OutputStream? = null
        var file: File? = null
        try {
            url = URL(urlStr)
            val urlConnection: URLConnection = url.openConnection()
            urlConnection.setConnectTimeout(5 * 1000)
            input = urlConnection.getInputStream()
            file = File.createTempFile("xxxx", "jpg")
            output = FileOutputStream(file)
            val byt = ByteArray(1024)
            var length = 0
            // 开始读取
            while (input.read(byt).also({ length = it }) != -1) {
                output.write(byt, 0, length)
            }
            input.close()
            output.close()
            println("下载完成")
        } catch (e: Exception) {
            e.printStackTrace()
            println("下载出错")
        }
        return file
    }

}